package com.example.memohehang.service.Impl;

import com.example.memohehang.common.R;
import com.example.memohehang.service.OssUploadService;
import com.example.memohehang.utils.PathUtils;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@Service
@Data//为成员变量生成get和set方法
@ConfigurationProperties(prefix = "local-storage")
public class LocalStorageServiceImpl implements OssUploadService{

//    @Value("${local-storage.path}")
//    private String storagePath;
    private String storagePath;


    @Override
    public R uploadImg(MultipartFile img) {
        String originalFilename = img.getOriginalFilename();
        String filePath = PathUtils.generateFilePath(originalFilename);

        File file = new File(storagePath + "/" + filePath);
        File dir = file.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }

        try {
            Files.write(Paths.get(file.toURI()), img.getBytes());
            return R.success(200, "操作成功", file.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
            return R.error(500, "文件上传失败");
        }
    }
}